/**
 * $Id: SQL.java 56 2008-11-07 09:12:56Z daniele.galdi $
 */
package it.edgeworks.dsession.impl.mysql;

import java.sql.*;

/**
 * @author Daniele Galdi
 * @version $Revision: 56 $
 */
public class SQL {

    // -----------------------------------------------------------------------
    // Check database
    // -----------------------------------------------------------------------

    public static final String CREATE_TABLE_SESSIONS =
            "create table if not exists sessions (" +
                    " session_id varchar(255)," +
                    " session_value blob, " +
                    " last_access timestamp, " +
                    " primary key (session_id)" +
                    ")";

    // -----------------------------------------------------------------------
    // Save session
    // -----------------------------------------------------------------------

    public static final String CREATE_SESSION =
            "insert into sessions (session_id, session_value) values (?, ?)";

    public static final String DROP_SESSION =
            "delete from sessions where session_id = ?";

    // -----------------------------------------------------------------------
    // Load session
    // -----------------------------------------------------------------------

    public static final String SELECT_SESSION =
            "select session_value from sessions " +
                    "where session_id = ?";

    // -----------------------------------------------------------------------
    // Session cleaner
    // -----------------------------------------------------------------------

    public static final String DROP_OLD_SESSIONS =
            "delete from sessions " +
                    "where last_access < date_sub(current_timestamp,interval ? minute);";

    // -----------------------------------------------------------------------
    // Sql utility
    // -----------------------------------------------------------------------    

    public static void close(Connection connection) {
        try {
            connection.close();
        } catch (Exception ignore) {
        }
    }

    public static void close(Statement st) {
        try {
            st.close();
        } catch (Exception ignore) {
        }
    }

    public static void close(ResultSet rs) {
        try {
            rs.close();
        } catch (Exception ignore) {
        }
    }

    public static void commit(Connection conn, boolean ok) {
        if (!ok) {
            try {
                conn.rollback();
            } catch (Exception ignore) {
            }
        } else {
            try {
                conn.commit();
            } catch (Exception ignore) {
            }
        }
    }
}
